/*
 * @author : TF-BJ-C064
 * @creation : 2014-6-9 下午3:29:07
 * @description : 
 *
 */

package com.action.park;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.log4j.Logger;

import com.action.system.LoginAction;
import com.base.BaseAction;
import com.base.UserBean;
import com.bean.ParkManager;
import com.bean.RulerInfo;
import com.bean.RulerMethod;
import com.bean.RulerRole;
import com.bean.SysUser;
import com.dao.RulerDao;
import com.service.ParkManagerService;
import com.util.Browser;
import com.util.GUtil;

public class ParkLogin extends BaseAction {

	private static final Logger log = Logger.getLogger(RulerDao.class);

	String captcha;

	private ParkManagerService service;
	private ParkManager parkManager;
	private Browser broswer;

	private List<ParkManager> list = null;

	String helpurl = "#";

	public void preLogin(){

		loginAction = "ParkLogin";
		this.addCookie("loginAction", loginAction);

		//get RedirectUrl from cookie
		if(RedirectUrl==null){
			Cookie cookie = GUtil.getCookieByName(request, "RedirectUrl");
			if(cookie!=null)
				RedirectUrl = cookie.getValue();
		}

		if(RedirectUrl!=null && !RedirectUrl.trim().isEmpty()){
			session.put("RedirectUrl", RedirectUrl);
			this.addCookie("RedirectUrl", RedirectUrl);
		}
	}

	@Override
	public String handle() throws Exception {

		this.setLoginAction("ParkLogin");
		this.setTitle( sc.getInitParameter("ParkTitle") );

		this.addCookie("loginAction", "LoginAction");

		String ret = this.checkBrowser();
		if( !ret.equals(GUtil.SUCCESS)){
			return ret;
		}

		this.preLogin();
		this.addCookie("loginAction", "");
		this.addCookie("RedirectUrl", "");

		if(method==null)
			return GUtil.LOGIN;
		if(method!=null ){
			if(method.endsWith("login"))
				return this.login();
			else 
				return this.logout();
		}
		if(title!=null){
			return GUtil.LOGIN;
		}
		else{
			this.setMsg("What you want, man ???");
			return GUtil.ERROR;
		}

	}

	public String checkBrowser(){
		if(IgnoreBrowser==null)
			IgnoreBrowser = (Boolean) session.get("IgnoreBrowser");
		if(IgnoreBrowser!=null && IgnoreBrowser==true){
			session.put("IgnoreBrowser", IgnoreBrowser);
		}else{
			broswer = new Browser(request);
			if(broswer.getName().startsWith("MSIE")){
				this.setMsg("请使用非IE浏览器,如使用的是360浏览器,请选择\"极速模式\",详见 <a href=\""+helpurl+"\">帮助</a>" +
						//	"&nbsp |&nbsp <font size=small><a href="+this.action+"?IgnoreBrowser=true >忽略并继续</a></font>" " +
						"  ");//"
				return GUtil.ERROR;
			}
		}
		return GUtil.SUCCESS;
	}


	//注销
	public String logout() throws Exception{
		this.addCookie("loginAction", "LoginAction");
		if(user!=null)
		{
			log.info("ParkLogin logout @ user:  "+user.getUserCode()+"["+user.getUserName()+"]  logout");
			System.out.println(" user:  "+user.getUserCode()+"["+user.getUserName()+"]  logout");
		}
		session.clear();
		return GUtil.LOGIN;
	}

	//登录
	public String login() throws Exception{

		String ip = GUtil.parseIp(request, response);

		List<Integer>  idlist =  new ArrayList<Integer>() ;
		List<RulerRole> rulerRoleList = null;
		List<RulerInfo> rulerInfolist = null;

		this.preLogin();
		session.put("RedirectUrl", "");
		this.addCookie("loginAction", "");

		//用户的session还未失效，暂时不需要再次通过数据库登录
		if(session.get("user")!=null && session.get("parkuser")!=null){
			user = (UserBean) session.get("user");
			if(RedirectUrl==null)
				RedirectUrl = (String) session.get("RedirectUrl");
			if( RedirectUrl !=null && !RedirectUrl.isEmpty() ){
				response.sendRedirect(RedirectUrl);
				return GUtil.NONE;
			}
			return GUtil.SUCCESS;
		}

		//通过查询数据库进行登录

		Long t1 = System.currentTimeMillis();
		//user = (UserBean) session.get("user");
		ParkManager pk = null;
		if(token!=null && userId!=null){
			//通过token登录
			//通过token登录
			pk = service.login(userId, token, ip);//开始登录

		}else{
			if (user == null) {
				log.info("来自 IP="+ip + " 的停车场用户请求登录");
				return LOGIN; // 浏览器输入 http://127.0.0.1/oa/LoginAction?method=login 返回空操作和空消息
			}
			if(user.getUserCode()==null || user.getUserCode().trim().isEmpty()){
				msg = "帐号不能为空";
				return GUtil.LOGIN;
			}
			if(token==null && (user.getUserPasswd()==null || user.getUserPasswd().trim().isEmpty()) ){
				msg = "密码不能为空";
				return GUtil.LOGIN;
			}

			if(parkManager==null)
				parkManager = new ParkManager();
			parkManager.setUserName(user.getUserCode());
			parkManager.setUserPasswd(user.getUserPasswd());
			pk = service.login(parkManager, ip);//开始登录
		}

		if(pk == null ){
			this.setMsg("用户名或密码错误!");
			log.info(msg+" ip="+ip);
			return GUtil.LOGIN;
		}
		if(pk.getStatus()!=1){
			this.setMsg("抱歉,用户状态["+pk.getStatusName()+"],如有疑问请联系管理员!");
			return GUtil.LOGIN;
		}

		if(user==null)
			user = new UserBean();
		user.setUser(pk);
		session.put("parkuser", pk);
		session.put("loginAction", "ParkLogin");
		user.setIp(ip);

		parkuser = pk;
		Long roleId = Long.valueOf(parkuser.getRole());//获取角色id

		log.info("----------------  ParkLogin login() -------------------------");

		Long t2 = System.currentTimeMillis();
		rulerRoleList = rulerService.rulerRole(roleId);//获取本用户的所有权限
		Long t3 = System.currentTimeMillis();

		if(rulerRoleList==null ){
			msg  = "您没有任何权限，如有疑问，请联系管理员";
			log.info(msg+" ip="+ip);
			return GUtil.LOGIN;
		}

		//获取所有权限
		for(RulerRole rr : rulerRoleList){
			idlist.add( rr.getRulerId() );
			//	log.info( rr.getRulerId()+"=" + rr.getRulerWord());
		}

		Long t4 = System.currentTimeMillis();
		rulerInfolist = (List<RulerInfo>) rulerService.queryRulerList(idlist);//根据权限ID(ruler id)获取对应的菜单
		List<RulerMethod> methodsList = rulerService.queryMethds(null, false);
		Long t5 = System.currentTimeMillis();

		Map<String, RulerInfo > rulermap = LoginAction.calcRoleRight(rulerRoleList, rulerInfolist, methodsList);

		session.put("parkuser", parkuser);
		session.put("user", user);
		session.put("rulermap", rulermap);
		//		session.put("rulerRoleList", rulerRoleList);//本用户的所有权限
		session.put("rulerInfolist", rulerInfolist);//本用户的菜单

		Long t6 = System.currentTimeMillis();
		log.info("ParkLogin.login()[登录成功][ip="+ip+" usercode="+user.getUserCode()+" login total takes "+(t6-t1)+"ms] " +
				"[获取本用户的所有权限 takes "+(t3-t2)+"ms ] [根据权限ID(ruler id)获取对应的菜单 "+(t5-t4)+"ms] ");

		//登录成功，返回指定页面
		if( RedirectUrl !=null && !RedirectUrl.trim().isEmpty() ){
			response.sendRedirect(RedirectUrl);
			return GUtil.NONE;
		}

		return GUtil.SUCCESS;
	}

	@Override
	public String query() throws Exception {
		return GUtil.NONE;
	}

	@Override
	public String add() throws Exception {
		return GUtil.NONE;
	}

	@Override
	public String update() throws Exception {
		return null;
	}

	@Override
	public String delete() throws Exception {
		return null;
	}

	@Override
	public String view() throws Exception {
		return null;
	}

	@Override
	public boolean validate(Object obj) throws Exception {
		return false;
	}

	/**
	 * @return the service
	 */
	public ParkManagerService getService() {
		return service;
	}

	/**
	 * @param service the service to set
	 */
	public void setService(ParkManagerService service) {
		this.service = service;
	}

	/**
	 * @return the parkManager
	 */
	public ParkManager getParkManager() {
		return parkManager;
	}

	/**
	 * @param parkManager the parkManager to set
	 */
	public void setParkManager(ParkManager parkManager) {
		this.parkManager = parkManager;
	}

	public String getCaptcha() {
		return captcha;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

}
